/**
 * 
 */
package com.ph.merchant.api.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ph.base.BaseController;
import com.ph.shopping.common.core.constant.CommonConstants;
import com.ph.shopping.common.core.customenum.ChargeEnum;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.customenum.RoleEnum;
import com.ph.shopping.common.core.customenum.TransCodeEnum;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.com.order.Constants;
import com.ph.shopping.common.util.com.order.CreateOrderUtil;
import com.ph.shopping.common.util.com.order.OrderBizCode;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.common.util.transform.MoneyTransUtil;
import com.ph.shopping.facade.member.entity.Member;
import com.ph.shopping.facade.member.service.IBankCardBindService;
import com.ph.shopping.facade.member.service.IMemberService;
import com.ph.shopping.facade.merchant.entity.*;
import com.ph.shopping.facade.merchant.request.UserBalanceRequest;
import com.ph.shopping.facade.merchant.service.IMerchantService;
import com.ph.shopping.facade.merchant.service.IUserBalance;
import com.ph.shopping.facade.merchant.vo.MerchantDetaileVo;
import com.ph.shopping.facade.merchant.vo.UserBalanceRecordVo;
import com.ph.shopping.facade.merchant.vo.UserBalanceVo;
import com.ph.shopping.facade.permission.vo.SessionRoleVo;
import com.ph.shopping.facade.permission.vo.SessionUserVo;
import com.ph.shopping.facade.profit.entity.UnlineSupplyChainProfit;

import org.apache.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @项目：phshopping-api-platform
 *
 * @描述：
 *
 * @作者： huangdd
 *
 * @创建时间：2017年3月14日
 *
 * @Copyright @2017 by huangdd
 */
@Controller
@RequestMapping("api/merchant")
public class MerchantController extends BaseController{

	@Reference(version="1.0.0")
	private IMerchantService iMerchantService;
	
	//会员接口，调用通过手机号获取会员信息 
	@Reference(version="1.0.0")
	private IMemberService iMemberService;
	
	@Reference(version="1.0.0")
	private IUserBalance iUserBalance;

    //银行卡绑定接口，用于获取银行卡信息
    @Reference(version = "1.0.0")
    private IBankCardBindService iBankCardBindService;
    
	/**
	 * 获取商户列表
	 * @return
	 */
	@RequestMapping(value="/list",method=RequestMethod.GET)
	@ResponseBody
	public Object getMerchantList(@ModelAttribute Merchant merchant,PageBean pagebean,HttpServletRequest request){
		//获取session，通过Session获取代理商id
		SessionUserVo sessionUserVo = getLoginUser();
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			//如果角色类型是商户，设置商户Id为用户Id去查询商户详情
			SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
			RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
			if("CITY_AGENT".equals(roleEnum.name()) || "COUNTY_AGENT".equals(roleEnum.name()) || "COMMUNITY_AGENT".equals(roleEnum.name())){
                if (merchant.getAgentId() == null || "".equals(merchant.getAgentId())) {
                    merchant.setAgentId((sessionUserVo.getId()));
                }
            }			
		}
		return iMerchantService.getMerchantList(merchant,pagebean);
	}
	/**
	 * 新增商户(涉及商户表 商户图片表)
	 * @param merchant
	 * @return
	 */
	@RequestMapping(value="/addMercahntAndMerchantImage",method=RequestMethod.POST)
	@ResponseBody
	public Object addMerchant(Merchant merchant,HttpServletRequest request,MerchantImage merchantImage){
		try {
			//获取图片对象
			String businesslicenseImage = request.getParameter("businesslicenseImage");
			String idCardImage1 = request.getParameter("idCardImage1");
			String idCardImage2 = request.getParameter("idCardImage2");
			String shopImage = request.getParameter("shopImage");
			List<MerchantImage>  list = new ArrayList<MerchantImage>(); 
			if(!"".equals(idCardImage1)){
		        list.add(new MerchantImage(businesslicenseImage,CommonConstants.BUSINESS_IMAGE_SORT, null, CommonConstants.BUSINESS_IMAGE_INT_TYPE, new Date(), new Date()));//类型1
			}
			if(!"".equals(idCardImage2)){
				list.add(new MerchantImage(idCardImage1,CommonConstants.IDCARD1_IMAGE_SORT, null, CommonConstants.IDCARD_IMAGE_INT_TYPE, new Date(), new Date()));//类型2
			}
			if(!"".equals(idCardImage2)){
				list.add(new MerchantImage(idCardImage2,CommonConstants.IDCARD2_IMAGE_SORT, null, CommonConstants.IDCARD_IMAGE_INT_TYPE, new Date(), new Date()));//类型2
			}
	        if(!"".equals(shopImage)){
	        	list.add(new MerchantImage(shopImage,CommonConstants.SHOP_IMAGE_SORT, null, CommonConstants.SHOP_IMAGE_INT_TYPE, new Date(), new Date()));//类型3
	        }

			//获取session
			SessionUserVo sessionUserVo = getLoginUser();
			
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				//2.设置创建人、 更新人
				merchant.setCreateId(sessionUserVo.getId());
				merchant.setUpdateId(sessionUserVo.getId());
			}

			merchant.setCreateTime(new Date());
			merchant.setUpdateTime(new Date());
			merchant.setStatus(CommonConstants.CHECK_PENDING);//新增时状态为0，待审核
	        //执行新增用户和图片
			merchant.setPositionId(merchant.getTownId());//将townId存到positionId中
	        return iMerchantService.addMerchant(merchant,list);
		} catch (Exception e) {
			return getResult(ResultEnum.ADD_MRRCHANT_EXCEPTION);
		}
	}
	/**
	 * 跳转修改商户和商户图片页面
	 * @return
	 */
	@RequestMapping(value="/toUpdateMerchantAndMerchantImage",method=RequestMethod.GET)
	@ResponseBody
	public Object toUpdateMerchantAndMerchantImage(Merchant merchant){
		try {
			Result detaileMerchant = iMerchantService.getMerchantDetailForUpdate(merchant);
			MerchantDetaileVo merchantDetaileVo = (MerchantDetaileVo)detaileMerchant.getData();
			ModelAndView mv=new ModelAndView("/merchant/merchantUpdate");
			mv.addObject("merchantVo", merchantDetaileVo);
			return mv;
		} catch (Exception e) {
			logger.error("获取商户信息异常:", e.getMessage());
			return "";
		}
	}
	/**
	 * 修改商户表和商户图片表
	 * @param merchant 
	 * @return
	 */
	@RequestMapping(value="/updateMerchantAndMerchantImage",method=RequestMethod.POST)
	@ResponseBody
	public Object updateMember(Merchant merchant,HttpServletRequest request){
		try {
			//获取图片对象
			String businesslicenseImage = request.getParameter("businesslicenseImage");
			String idCardImage1 = request.getParameter("idCardImage1");
			String idCardImage2 = request.getParameter("idCardImage2");
			String shopImage = request.getParameter("shopImage");
			List<MerchantImage>  list = new ArrayList<MerchantImage>(); 
			if(!"".equals(businesslicenseImage)){
		        list.add(new MerchantImage(businesslicenseImage,1, null, 1, new Date(), new Date()));//类型1
			}
			if(!"".equals(idCardImage1)){
				list.add(new MerchantImage(idCardImage1,2, null, 2, new Date(), new Date()));//类型2
			}
	        if(!"".equals(idCardImage2)){
	        	list.add(new MerchantImage(idCardImage2,3, null, 2, new Date(), new Date()));//类型2
	        }
	        if(!"".equals(shopImage)){
	        	list.add(new MerchantImage(shopImage,4, null, 3, new Date(), new Date()));//类型3 
	        }
	    	
	        //获取session
			SessionUserVo sessionUserVo = getLoginUser();
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				//2.设置创建人、 更新人
				merchant.setUpdateId(sessionUserVo.getId());
			}
			merchant.setUpdateTime(new Date());
			
	        //执行新增用户和图片
	        return iMerchantService.updateMerchant(merchant,list);
		} catch (Exception e) {
			return getResult(ResultEnum.UPDATE_MRRCHANT_EXCEPTION);
		}
	}
	
	/**
	 * 商户详细
	 * @param merchant
	 * @return
	 */
	@RequestMapping(value="/merchantDetail",method=RequestMethod.GET)
	@ResponseBody
	public Object detaileMerchant(Merchant merchant){
		
		//获取session，通过Session获取用户Id作为商户Id
		SessionUserVo sessionUserVo = getLoginUser();
		
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			//如果角色类型是商户，设置商户Id为用户Id去查询商户详情
			SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
			RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
			if("MERCHANT".equals(roleEnum.name())){
				merchant.setId(sessionUserVo.getId());
			}
		}
		
		try {
			Result detaileMerchant = iMerchantService.detaileMerchant(merchant);
			MerchantDetaileVo merchantDetaileVo = (MerchantDetaileVo)detaileMerchant.getData();
			ModelAndView mv=new ModelAndView("/merchant/merchantDetail");
			mv.addObject("merchantVo", merchantDetaileVo);
			return mv;
		} catch (Exception e) {
			logger.error("获取商户信息异常:", e.getMessage());
			return "";
		}
	}
	
	/**
	 * 
	 *  跳转商户余额记录页面（根据id获取余额）
	 * @param 
	 * @return
	 */
	@RequestMapping(value="/merchantBalancePage",method=RequestMethod.GET)
	public Object merchantBalancePage(@ModelAttribute UserBalanceVo userBalanceVo){

		//获取session
		SessionUserVo sessionUserVo = getLoginUser();
		
		ModelAndView mv=new ModelAndView("/merchant/balanceMerchantList");
		try {
			UserBalance userBalance = new UserBalance();
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				
				SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
				RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
				
				//如果角色类型是商户，设置商户Id去查询余额记录，否则为平台下的余额记录
				if(roleEnum.equals(RoleEnum.MERCHANT)&& (userBalanceVo.getManageId()==null||userBalanceVo.getManageId().equals(""))){
					userBalance.setManageId(sessionUserVo.getId());
				}else{
					userBalance.setManageId(userBalanceVo.getManageId());
				}
			}
		
			//根据ManagerId查询商户名称
			String merchantName = "";
			Merchant merchant = new Merchant();
			merchant.setId(userBalance.getManageId());
			MerchantDetaileVo merchantVo = (MerchantDetaileVo) iMerchantService.getMerchantDetailForUpdate(merchant).getData();
			if(merchantVo!=null){
				merchantName = merchantVo.getMerchantName();
			}
			userBalanceVo.setUserName(merchantName);
			
			Result result = iMerchantService.getUserBalance(userBalance);
			if(result.getData()==null){
				userBalanceVo.setManageId(userBalance.getManageId());
				userBalanceVo.setBalance(new BigDecimal("0"));
			}else{
				UserBalance userBalance2 = (UserBalance) result.getData();
				userBalanceVo.setManageId(userBalance2.getManageId());
				userBalanceVo.setBalance(new BigDecimal(userBalance2.getBalance()));
			}

			mv.addObject("userBalanceVo", userBalanceVo);
			return mv;
		} catch (BizException e) {
			mv.addObject("userBalanceVo", userBalanceVo);
			logger.error("获取商户余额异常:", e.getMessage());
			return mv;
		}
		
	}
	
	/**
	 * 查询商户余额记录
	 */
	@RequestMapping(value="/merchantBalanceList",method=RequestMethod.GET)
	@ResponseBody
	public Object balanceMerchant(@ModelAttribute PageBean pagebean,@ModelAttribute UserBalanceRecordVo userBalanceRecordVo){
		try{
			Result result = iMerchantService.getUserBalanceRecordVoList(pagebean,userBalanceRecordVo);
			return result;
		}catch(BizException e){
			e.printStackTrace();
			logger.error("获取商户余额记录异常:", e.getMessage());
			return getResult(ResultEnum.USER_BALANCE_RECORD_EXCEPTION);
		}
	}
	
	/**
	 * 跳转商户列表页面
	 * @return
	 */
	@RequestMapping(value="/listPage",method=RequestMethod.GET)
	public String merchantPage(HttpServletRequest request){
		SessionUserVo sessionUserVo = getLoginUser();
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
			request.setAttribute("roleId", sessionRoleVo.getId());//放到前端去判断如果是社区代理不让他新增商户
		}
		return "/merchant/merchantList";
	}
	/**
	 * 跳转待审核商户列表页面
	 * @return
	 */
	@RequestMapping(value="/examineListPage",method=RequestMethod.GET)
	public String examineMerchantList(){
		return "/merchant/examineMerchantList";
	}
	/**
	 * 跳转新增商户和商户图片页面
	 * @return
	 */
	@RequestMapping(value="/addMerchantAndMerchantImage",method=RequestMethod.GET)
	public String addMerchantAndMerchantImage(){
		return "/merchant/merchantAdd";
	}
	/**
	 * 修改状态
	 * 状态  审核未通过0  审核未通过2  审核通过正常1 冻结  3
	 * @param merchant
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/updateMerchatStatues",method=RequestMethod.POST)
	public Object updateMerchatStatues(Merchant merchant, HttpServletRequest request){
		try{
			//获取session
			SessionUserVo sessionUserVo = getLoginUser();
			//设置 更新人
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				merchant.setUpdateId(sessionUserVo.getId());
			}
			//设置 更新时间
			merchant.setUpdateTime(new Date());
			
	    	if(merchant.getStatus()==3){
	    		//1.清空登录session
	    		sessionUserVo.getId();
				request.getSession().removeAttribute(merchant.getMerchantTel());
	    	}
			Result result = iMerchantService.updateMerchatStatues(merchant);
			if(result.getCode().equals(ResultEnum.ENTITY_AGENT_HAVE_EXCEPTION.getCode())){
				return getResult(ResultEnum.ENTITY_AGENT_HAVE_EXCEPTION);
			}
		}catch(BizException e){
			e.printStackTrace();
			return getResult(ResultEnum.CONGEALYES_AGENT_EXCEPTION);//返回短信发送失败的异常
		}
		return getResult(ResultEnum.SUCCESS);
	}
	/**
	 * 根据推广师电话自动获取推广师姓名
	 * @param merchant  
	 * @return
	 */
	@RequestMapping(value="/getPromoterNameByTel",method=RequestMethod.POST)
	@ResponseBody
	public Result getPromoterNameByTel(@ModelAttribute Merchant merchant){
		try {
			Member member = (Member) iMemberService.getMemberInfoByMobile(merchant.getPromoterTel()).getData();
			if(member!=null&&member.getMemberName()!=null&&member.getIsMarketing()==Byte.valueOf(CommonConstants.IS_PROMOTER)){
				return getResult(ResultEnum.SUCCESS, member.getMemberName());
			}else{
				return getResult(ResultEnum.PROMOTER_NON_EXISTENT, "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return getResult(ResultEnum.PROMOTER_NON_EXISTENT);
		}			
	}	
	/**
	 * 商户或者代理提现(分润表中确认提现后操作用户余额)
	 */
	@RequestMapping("userWithdrawals")
	@ResponseBody
	public Result userWithdrawals(UnlineSupplyChainProfit unlineSupplyChainProfit,String type) {
		Result result = getResult(ResultEnum.SUCCESS);
		try {
			if("1".equals(type)){//提现
				//首先判断用户金额是否充足
				UserBalance userBalance = new UserBalance();
				userBalance.setManageId(unlineSupplyChainProfit.getWithdrawalsId());
				Result userBalance2 = iUserBalance.getUserBalance(userBalance);
				UserBalance withdrawalsBalance = (UserBalance)userBalance2.getData();
				if(MoneyTransUtil.transMultiDouble(unlineSupplyChainProfit.getPrice())  > withdrawalsBalance.getBalance().longValue()){//判断余额是否充足
					logger.debug("用户余额不充足");
					//余额不足更改状态也是改提现表和分润表中关于提现的状态
					if(unlineSupplyChainProfit.getOrderType() == 2){//商户提现失败
						iUserBalance.updateMerchantWithdrawals(unlineSupplyChainProfit.getOrderNo(), new Integer(-1));
					}else{
						iUserBalance.updateAgentWithdrawals(unlineSupplyChainProfit.getOrderNo(), new Integer(-1));
					}
					iUserBalance.updateUserBalanceStatus(unlineSupplyChainProfit.getOrderNo(), new Integer(3));
					return getResult(ResultEnum.NOENOUGH_MONEY_EXCEPTION);
				}
				//如果 余额充足进行更改余额  判断商户提现还是代理提现
				if(unlineSupplyChainProfit.getOrderType() == 2){//商户提现
					int ret1 = iUserBalance.userBalanceTrade(unlineSupplyChainProfit.getWithdrawalsId(), TransCodeEnum.MERCHANT_WITHDRAWALS, 0, MoneyTransUtil.transMultiDouble(unlineSupplyChainProfit.getPrice()) ,null,unlineSupplyChainProfit.getOrderNo());
				}else{//代理提现
					int ret2 = iUserBalance.userBalanceTrade(unlineSupplyChainProfit.getWithdrawalsId(), TransCodeEnum.AGENT_WITHDRAWALS, 0, MoneyTransUtil.transMultiDouble(unlineSupplyChainProfit.getPrice()),null,unlineSupplyChainProfit.getOrderNo());
				}
			}else{//直接审核不通过
				if(unlineSupplyChainProfit.getOrderType() == 2){//商户提现
					iUserBalance.updateMerchantWithdrawals(unlineSupplyChainProfit.getOrderNo(), new Integer(-1));
				}else{
					iUserBalance.updateAgentWithdrawals(unlineSupplyChainProfit.getOrderNo(), new Integer(-1));
				}
				iUserBalance.updateUserBalanceStatus(unlineSupplyChainProfit.getOrderNo(), new Integer(3));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("余额交易失败",e.getMessage());
			return getResult(ResultEnum.UPDAET_USER_MONEY_EXCEPTION);
		}
		return  result;
	}
	

	/**
	 * 跳转到充值页面
	 * @author 刘颖
	 * @return
	 */
	@RequestMapping(value = "/chargeMerchantPage", method = RequestMethod.GET)
	public Object chargeMerchantPage(@ModelAttribute UserBalanceVo userBalanceVo) {

		//获取session
		SessionUserVo sessionUserVo = getLoginUser();
		
		ModelAndView mv=new ModelAndView("/merchant/chargeMerchantPage");
		
		try {
			UserBalance userBalance = new UserBalance();
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				
				SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
				RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
				
				//如果角色类型是商户，设置商户Id去查询余额记录，否则为平台下的余额记录
				if("MERCHANT".equals(roleEnum.name())){
					userBalance.setManageId(sessionUserVo.getId());
				}else{
					userBalance.setManageId(userBalanceVo.getManageId());
				}
			}
		
			Result result = iMerchantService.getUserBalance(userBalance);
			if(result.getData()==null){
				userBalanceVo.setManageId(userBalance.getManageId());
				mv.addObject("userBalanceVo", userBalanceVo);
			}else{
				mv.addObject("userBalanceVo", result.getData());
			}
			return mv;
		} catch (BizException e) {
			mv.addObject("userBalanceVo", userBalanceVo);
			logger.error("获取商户余额异常:", e.getMessage());
			return mv;
		}
		
//		//1.通过代理商Id获取银行卡信息
//		Result result = iBankCardBindService.getBankCardInfo(sessionUserVo.getId(), MemberEnum.PLATFORM_BANK.getCode());
//		BankCardBindInfoDto bankCardBindInfoDto =  (BankCardBindInfoDto) result.getData();
//		if(bankCardBindInfoDto!=null){
//			userBalanceVo.setBankId(bankCardBindInfoDto.getBankId());//绑定id
//			userBalanceVo.setBankName(bankCardBindInfoDto.getBankName());//银行名称
//			userBalanceVo.setBindPhone(bankCardBindInfoDto.getBindPhone());//绑定手机号
//			userBalanceVo.setCardNum(bankCardBindInfoDto.getCardNum());//卡号
//			userBalanceVo.setOwnName(bankCardBindInfoDto.getOwnName());//银行卡所属人
//		}

	}

	/**
	 * 跳转到提现页面
	 * @author 刘颖
	 * @return
	 */
	@RequestMapping(value = "/drawcashMerchantPage", method = RequestMethod.GET)
	public Object drawcashMerchantPage(@ModelAttribute UserBalanceVo userBalanceVo) throws Exception{

		//获取session
		SessionUserVo sessionUserVo = getLoginUser();
		
		ModelAndView mv=new ModelAndView("/merchant/drawcashMerchantPage");
		try {
			UserBalance userBalance = new UserBalance();
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				
				SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
				RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
				
				//如果角色类型是商户，设置商户Id去查询余额记录，否则为平台下的余额记录
				if("MERCHANT".equals(roleEnum.name())){
					userBalance.setManageId(sessionUserVo.getId());
				}else{
					userBalance.setManageId(userBalanceVo.getManageId());
				}
			}
		
			Result result = iMerchantService.getUserBalance(userBalance);
			if(result.getData()!=null){
				userBalance = (UserBalance) result.getData();
				userBalanceVo.setBalance(new BigDecimal(userBalance.getBalance()).divide(new BigDecimal("10000"), 2, BigDecimal.ROUND_FLOOR) );
			}else{
				userBalanceVo.setBalance(new BigDecimal("0"));
			}

			userBalanceVo.setManageId(userBalance.getManageId());
			//查询当天提现总额，提现总额不超过1万
			MerchantDrawcashRecord merchantDrawcashRecord = new MerchantDrawcashRecord();
			merchantDrawcashRecord.setMerchantId(userBalance.getManageId());
			BigDecimal drawcashMoneyToday = iMerchantService.getDrawcashMoneyToday(merchantDrawcashRecord);
			if(drawcashMoneyToday!=null){
				userBalanceVo.setDrawcashMoneyToday(((new BigDecimal("10000")).subtract(drawcashMoneyToday)).setScale(2,BigDecimal.ROUND_FLOOR));
			}else{
				userBalanceVo.setDrawcashMoneyToday(new BigDecimal("10000"));
			}

			//查询待审核状态的提现总额，待审核提现总额不超过总余额
			merchantDrawcashRecord.setStatus(CommonConstants.CHECK_PENDING);
			BigDecimal drawcashStatusPendingTotal = iMerchantService.getDrawcashStatusPendingTotal(merchantDrawcashRecord);
			if(drawcashStatusPendingTotal!=null){
				userBalanceVo.setDrawcashStatusPendingTotal(drawcashStatusPendingTotal);
			}else{
				userBalanceVo.setDrawcashStatusPendingTotal(new BigDecimal("0"));
			}
			
			//可申请提现的余额
			userBalanceVo.setCanApplyDrawcashMoney(((userBalanceVo.getBalance()).subtract(userBalanceVo.getDrawcashStatusPendingTotal())).setScale(2,BigDecimal.ROUND_FLOOR));
			mv.addObject("userBalanceVo", userBalanceVo);
			
			return mv;
		} catch (BizException e) {
			mv.addObject("userBalanceVo", userBalanceVo);
			logger.error("获取商户余额异常:", e.getMessage());
			return mv;
		}
		
//		//1.通过代理商Id获取银行卡信息
//		Result result = iBankCardBindService.getBankCardInfo(sessionUserVo.getId(), MemberEnum.PLATFORM_BANK.getCode());
//		BankCardBindInfoDto bankCardBindInfoDto =  (BankCardBindInfoDto) result.getData();
//		if(bankCardBindInfoDto!=null){
//			userBalanceVo.setBankId(bankCardBindInfoDto.getBankId());//绑定id
//			userBalanceVo.setBankName(bankCardBindInfoDto.getBankName());//银行名称
//			userBalanceVo.setBindPhone(bankCardBindInfoDto.getBindPhone());//绑定手机号
//			userBalanceVo.setCardNum(bankCardBindInfoDto.getCardNum());//卡号
//			userBalanceVo.setOwnName(bankCardBindInfoDto.getOwnName());//银行卡所属人
//		}

	}


	/**
	 * 充值的上一步，创建订单，返回订单号
	 * @param userBalanceVo
	 * @return
	 * @author 刘颖
	 */
	@ResponseBody
	@RequestMapping(value="/chargeMerchantCreateOrder",method=RequestMethod.POST)
	public Object chargeMerchantCreateOrder(@ModelAttribute("userBalanceVo") UserBalanceVo userBalanceVo) throws Exception  {
		//1.生成订单号，用于充值记录
		String orderNum = CreateOrderUtil.createOrderCode(OrderBizCode.MERCHANT_CAHRGE);
		//2.生成充值记录
		MerchantChargeRecord merchantChargeRecord = new MerchantChargeRecord();
		merchantChargeRecord.setMerchantId(userBalanceVo.getManageId());
		merchantChargeRecord.setScore(userBalanceVo.getChargeMoney().multiply(new BigDecimal(10000)));
		merchantChargeRecord.setOrderNum(orderNum);
		merchantChargeRecord.setChargeType(ChargeEnum.CHARGE_TYPE.getCode());
		merchantChargeRecord.setCreater(userBalanceVo.getManageId());
		merchantChargeRecord.setCreateTime(new Date());
		iMerchantService.addMerchantChargeRecord(merchantChargeRecord);
		//返回订单号
		return getResult(ResultEnum.SUCCESS,orderNum);
	}

	/**
	 * 提现
	 * @param userBalanceVo
	 * @return
	 * @author 刘颖
	 */
	@ResponseBody
	@RequestMapping(value="/drawcashMerchant",method=RequestMethod.POST)
	public Object drawcashMerchant(@ModelAttribute("userBalanceVo") UserBalanceVo userBalanceVo) throws Exception  {
		//1.生成订单号，用于提现记录
		String orderNum = CreateOrderUtil.createOrderCode(OrderBizCode.MERCHANT_DRAW_CASH);
		//写提现表
		MerchantDrawcashRecord merchantDrawcashRecord = new MerchantDrawcashRecord();
		merchantDrawcashRecord.setMerchantId(userBalanceVo.getManageId());
		merchantDrawcashRecord.setScore(userBalanceVo.getDrawcashMoney().multiply(new BigDecimal(10000)));
		merchantDrawcashRecord.setStatus(CommonConstants.CHECK_PENDING);//待审核
		merchantDrawcashRecord.setDrawcashNo(orderNum);//订单号
		merchantDrawcashRecord.setCreateDate(new Date());
		merchantDrawcashRecord.setBankName(userBalanceVo.getBankName());
		merchantDrawcashRecord.setDrawcashIp("");//这里要设置Ip
		merchantDrawcashRecord.setReceiver(userBalanceVo.getOwnName());
		merchantDrawcashRecord.setBankNo(userBalanceVo.getCardNum());
		merchantDrawcashRecord.setCreater(userBalanceVo.getManageId());
		merchantDrawcashRecord.setCreateTime(new Date());
		iMerchantService.addMerchantDrawcashRecord(merchantDrawcashRecord);
		return getResult(ResultEnum.SUCCESS);
	}
	/**
	 * 获取区域列表
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getAllPosition",method=RequestMethod.POST)
	public Object getPosition(String pid , String type){
		Result positionByIdAndType = iMerchantService.getPositionByIdAndType(pid, type);
		return positionByIdAndType;
	}
}
